<?

//Initiate Authenticate
SecurityRedirect ();
//error_reporting(E_ALL);


//initiate Vars
define("PRIMARY_KEY","jo_id");
$FileName       = "ais_transaction_shipping_doc.php";
$FileTemplate   = "ais_transaction_shipping_doc_form.html";
$SubHeaderTitle = "Shipping Document";
$TableName      = "tbljoborder";
$HTMLFormName   = "JOForm";
$PRIMARY_KEY    = PRIMARY_KEY;
$PRIMARY_VALUE  = GetParam($PRIMARY_KEY,"");

$ServerURL = ServerURL;
$uploadDirModule = "shippingDoc";
$upload_dir = $ROOT_DIR.$ROOT_UPLOAD_DIR."/".$uploadDirModule."/";
$uploadList = "";

$MaxGrid        = "20";
$KTRASL                = GetOfficeID();
//$HTMLFormName2  = "BudgetForm";

$FormAction    = $FileName . "?" . AddParam(GetQueryString("QueryString", ""),"form","$HTMLFormName");
$FormEncType   = "application/x-www-form-urlencoded";
//$PMode         = "";

//Initiate Grid Fields;
$FormFields    = array("jo_id"=>"","jo_code"=>"","doc_ref"=>"","project_id"=>"","debtur"=>"","staff_id"=>"","jo_date"=>"date","rbt_idr"=>"","rbt_usd"=>"","rat_idr"=>"","rat_usd"=>"","jo_status"=>"","jo_appv_status"=>"");
buildsqlfield ("$TableName", $FormFields);


//Variable declaration
$jo_id = GetParam("jo_id","");
$project_id = GetParam("project_id","");
$redirect = GetParam("redirect","");

//Convert Date

$etd = convert_date(GetParam("etd",""));
$eta = convert_date(GetParam("eta",""));
$hawe_no_ori = convert_date(GetParam("hawe_no_ori",""));
$hawe_no_cpy = convert_date(GetParam("hawe_no_cpy",""));
$bl_no_ori = convert_date(GetParam("bl_no_ori",""));
$bl_no_cpy = convert_date(GetParam("bl_no_cpy",""));
$invoice_no_ori = convert_date(GetParam("invoice_no_ori",""));
$invoice_no_cpy = convert_date(GetParam("invoice_no_cpy",""));
$packing_list_ori = convert_date(GetParam("packing_list_ori",""));
$packing_list_cpy = convert_date(GetParam("packing_list_cpy",""));
$cert_ori = convert_date(GetParam("cert_ori",""));
$cert_cpy = convert_date(GetParam("cert_cpy",""));
$insurance_ori = convert_date(GetParam("insurance_ori",""));
$insurance_cpy = convert_date(GetParam("insurance_cpy",""));
$loa_ori = convert_date(GetParam("loa_ori",""));
$loa_cpy = convert_date(GetParam("loa_cpy",""));
$stat_con_ori = convert_date(GetParam("stat_con_ori",""));
$stat_con_cpy = convert_date(GetParam("stat_con_cpy",""));
$recom_loa_ori = convert_date(GetParam("recom_loa_ori",""));
$recom_loa_cpy = convert_date(GetParam("recom_loa_cpy",""));
$recom_lartas_ori = convert_date(GetParam("recom_lartas_ori",""));
$recom_lartas_cpy = convert_date(GetParam("recom_lartas_cpy",""));

//Convert Date


$today = date("Y-m-d");

//End Variable declaration


//buildsqlfield ("$TableName", $FormFields);

//Leave Here Untouch
$FormCName     = BuildHTMLField($FormFields,"name");
$FormCValue    = BuildHTMLField($FormFields,"value");
$FormHName     = BuildHTMLField($FormFields,"name",1);
$FormHValue    = BuildHTMLField($FormFields,"value",1);

//************ FORM ACTION **************



if (GetParam("FormAction","")=="Save") 
{
				  
		$DBConnection->dbc->query("DELETE FROM tblshipping_doc WHERE jo_id='".$jo_id."'");
		$DBConnection->dbc->query("DELETE FROM tblshipping_doc_remarks WHERE jo_id='".$jo_id."'");
		
		//Insert into tblshipping_doc_remarks
		FormSave("tblshipping_doc_remarks", "date_remarks", array("jo_id"=>"","date_remarks"=>"date","day_remarks"=>"","text_remarks"=>""),"","jo_id","");

		$DBConnection->InsertGrid();
		
		//Insert into tblshipping_doc
		$DBConnection->dbc->query("INSERT INTO tblshipping_doc(jo_id,shipment_no,receive_from,port_loading,charges_port,delivery_site,bcii_no,no_aju_pib,laks_cc,pros_by,voy,etd,eta,gdg,
								   lartas_1,lartas_2,lartas_3,lartas_4,lartas_5,hawe_no,hawe_no_ori,hawe_no_cpy,bl_no_ori,bl_no_cpy,invoice_no_ori,invoice_no_cpy,packing_list,
								   packing_list_ori,packing_list_cpy,cert,cert_ori,cert_cpy,insurance,insurance_ori,insurance_cpy,loa,loa_ori,loa_cpy,
								   stat_con,stat_con_ori,stat_con_cpy,recom_loa,recom_loa_ori,recom_loa_cpy,recom_lartas,recom_lartas_ori,recom_lartas_cpy)
								   
								   VALUES('".$jo_id."','".GetParam("shipment_no","")."','".GetParam("receive_from","")."','".GetParam("port_loading","")."','".GetParam("charges_port","")."','".GetParam("delivery_site","")."'
								  ,'".GetParam("bcii_no","")."','".GetParam("no_aju_pib","")."','".GetParam("laks_cc","")."','".GetParam("pros_by","")."','".GetParam("voy","")."','".$etd."'
								  ,'".$eta."','".GetParam("gdg","")."','".GetParam("lartas_1","")."','".GetParam("lartas_2","")."','".GetParam("lartas_3","")."'
								  ,'".GetParam("lartas_4","")."','".GetParam("lartas_5","")."','".GetParam("hawe_no","")."','".$hawe_no_ori."','".$hawe_no_cpy."'
								  ,'".$bl_no_ori."','".$bl_no_cpy."','".$invoice_no_ori."','".$invoice_no_cpy."','".GetParam("packing_list","")."','".$packing_list_ori."'
								  ,'".$packing_list_cpy."','".GetParam("cert","")."','".$cert_ori."','".$cert_cpy."','".GetParam("insurance","")."','".$insurance_ori."'
								  ,'".$insurance_cpy."','".GetParam("loa","")."','".$loa_ori."','".$loa_cpy."','".GetParam("stat_con","")."','".$stat_con_ori."'
								  ,'".$stat_con_cpy."','".GetParam("recom_loa","")."','".$recom_loa_ori."','".$recom_loa_cpy."','".GetParam("recom_lartas","")."','".$recom_lartas_ori."','".$recom_lartas_cpy."')");
		
		
  
		
		$DBConnection->dbc->query("UPDATE ".$TableName." SET bl_no='".GetParam("bl_no","")."',invoice_no='".GetParam("invoice_no","")."' WHERE jo_id='".$jo_id."'");
	   
		//$DBConnection->dbc->query("UPDATE ".$TableName." SET doc_ref='".GetParam("doc_ref","")."',project_id='".GetParam("project_id","")."',debtur='".GetParam("debtur","")."',staff_id='".GetParam("staff_id","")."',jo_date = '".$jo_date."',bl_no='".GetParam("bl_no","")."',invoice_no='".GetParam("invoice_no","")."',vessel='".GetParam("vessel","")."',rbt_idr = '".GetParam("rbt_idr","")."',rbt_usd = '".GetParam("rbt_usd","")."',rat_idr = '".GetParam("rat_idr","")."',rat_usd = '".GetParam("rat_usd","")."',jo_appv_status = '".GetParam("jo_appv_status","")."' WHERE jo_id='".$jo_id."'");
		SetLogActivity($TransNo,"Update","");
		
		//CheckAndUpdateCache ($TransNo);


	//header("Location: $FileName?PageMode=Form&jo_id=$jo_id");
	redirectMeta($FileName."?PageMode=Form&jo_id=".$jo_id);	
	exit;
	
}

if (GetParam("FormAction","")=="Delete") {
//      print "Deleted"."<br>\n";
			$SQL = "DELETE FROM tbljoborder WHERE jo_id='".GetParam("jo_id","")."'";
			$DBConnection->dbc->query($SQL);
			$SQL = "DELETE FROM tbljoactivity WHERE jo_id='".GetParam("jo_id","")."'";
			$DBConnection->dbc->query($SQL);
			SetLogActivity($TransNo,"Delete","");
	
	//header("Location: $FileName?PageMode=Form");
	redirectMeta($FileName."?PageMode=Form");
	exit;
}



//Counting Cargo

$container_40 = 0;
$container_20 = 0;
$cargo_jumlah= 0;
$cargo_berat = 0;
$cargo_volume = 0;

$SQLCargoCount = "SELECT * FROM tbljocargo 
                 WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' ORDER BY cargo_id";

$ResultCargoCount  = $DBConnection->dbc->get_results($SQLCargoCount,ARRAY_A);

if(!empty($ResultCargoCount))
{
   
   foreach($ResultCargoCount as $cargo_id => $cargo_val)
	{
		if($cargo_val['cargo_type'] == '6')
		 {
			$container_40+= intval($cargo_val['cargo_jumlah']); 
		 }
		 
		if($cargo_val['cargo_type'] == '7')
		 {
			$container_20+= intval($cargo_val['cargo_jumlah']); 
		 }
		 		 
		 $cargo_jumlah+= intval($cargo_val['cargo_jumlah']);
		 $cargo_berat+= intval($cargo_val['cargo_berat']); 
		 $cargo_volume+= intval($cargo_val['cargo_volume']);
		 
	}
   	
}

else
{
	$container_40 = 0;
	$container_20 = 0;
	$cargo_jumlah = 0;
    $cargo_berat = 0;
    $cargo_volume = 0;
}


//End Counting Cargo




//Field Verification
$Verification  = "False";
$SessionVar    = md5(microtime());
//$SessionVar    = "Stuck";


//$VerifyFields = array("services_id1" => "Services","qty1" => "Quantity","unit1"=>"Unit","curr1"=>"Currency","rate1"=>"Rate");

$VerifyFields = array();
VerifyHTML ($HTMLFormName,$VerifyFields,$SessionVar);


$InitFunction = "Masking();Masking2();";

$VerifyGrids = array();
$Masking1 = BuildMasking ($HTMLFormName,MutatorFields($FormFields,($MaxGrid+$Count)));
$Masking2 = BuildMasking ($HTMLFormName,array(),"2");
$JSMasks  = $Masking1.$Masking2;
Init($SessionVar,$JSMasks);
FormGridHTML ($HTMLFormName,$VerifyGrids,$Count,$MaxGrid,$SessionVar);



//************ SET FORM MODE ***************
$USER_CANPRINT_TAX="0";

if (GetParam(PRIMARY_KEY,"")) {
        $FormMode = "Edit";
        $USER_CANPRINT="1";
        $SQL ="SELECT vat FROM ais_memorial WHERE nobkt='".GetParam(PRIMARY_KEY,"")."' AND urut=999 ";
        if (strlen($DBConnection->dbc->get_var($SQL))) $USER_CANPRINT_TAX="1";
} else {
        $FormMode = "Add";
        $USER_CANPRINT="0";
}
//******* DATABASE GRID QUERY ***********

$SQL = "SELECT ".BuildFields($FormFields)." FROM `$TableName`";
if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") {
    $SQL      = $SQL."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."'";
    $SQL     .= " AND ktrasl='".GetOfficeID()."'";
    $SQLGrid  = $SQL." ORDER BY urut";
}

//******* SHOW FORM CONTENT *********
$TBS = new clsTinyButStrong ;
$TBS->LoadTemplate($MOD_TEMPLATE_DIR."/".$FileTemplate);

//********************************* HTML Header ******************************************



//edited by Adit van Smith



//GET Kurs
$SQLGetKurs = "SELECT * FROM ais_kurssi WHERE curr = 'USD' ORDER BY tglbkt DESC";
$ResultGetKurs  = $DBConnection->dbc->get_row($SQLGetKurs,ARRAY_A);   

$kursUSD = $ResultGetKurs['rate'];
//END GET Kurs



//Project Get Header

if(GetParam(PRIMARY_KEY,"") != '' && GetParam(PRIMARY_KEY,"") != 'AUTO NUMBERED BY SYSTEM')
{  
   $SQLProject = "SELECT a.*,b.*,c.*,d.*, 
			      if(a.jo_appv_status = 'draft', 'Draft', if(a.jo_appv_status = 'wait_approved', 'Wait for Approval', if(a.jo_appv_status = 'approved', 'Approved', 'No Approval Status'))) as approval_status 
			      FROM `$TableName` as a ";
   $SQLProject.= "JOIN tblproject as b ON a.project_id = b.project_id "; 
   $SQLProject.= "JOIN ".$DBGeneral.".tblstaff as c ON a.staff_id = c.staff_id ";
   $SQLProject.= "JOIN tbldebtur as d ON a.debtur = d.CUCODE ";
   $SQLProject.= "WHERE a.".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' ORDER BY a.".PRIMARY_KEY." ASC";

   $ResultProject  = $DBConnection->dbc->get_results($SQLProject,ARRAY_A);   
   
   
   $SQLProject2 = "SELECT a.*, b.*, b.nama as laks_name FROM tblshipping_doc as a ";
   $SQLProject2.= "JOIN ".$DBGeneral.".tblstaff as b ON a.laks_cc = b.nik "; 
   $SQLProject2.= "WHERE a.".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' ORDER BY a.shipping_doc_id ASC";

   $ResultProject2 = $DBConnection->dbc->get_results($SQLProject2,ARRAY_A);   
   
   if(empty($ResultProject2))
   {
	   $ResultProject2 = array(
	   
	       array(
		      "shipment_no" => "",
	          "receive_from" => "",
	          "port_loading" => "",
	          "charges_port" => "",
	          "delivery_site" => "",
	          "bcii_no" => "",
	          "no_aju_pib" => "",
	          "laks_cc"=>"",
	          "pros_by"=>"",
	          "voy"=>"",
	          "etd"=>$today,
	          "eta"=>$today,
	          "gdg"=>"",
	          "lartas_1"=>"",
	          "lartas_2"=>"",
	          "lartas_3"=>"",
	          "lartas_4"=>"",
	          "lartas_5"=>"",
	          "hawe_no"=>"",
	          "hawe_no_ori"=>$today,
	          "hawe_no_cpy"=>$today,
	          "bl_no_ori"=>$today,
	          "bl_no_cpy"=>$today,
	          "invoice_no_ori"=>$today,
	          "invoice_no_cpy"=>$today,
	          "packing_list"=>"",
	          "packing_list_ori"=>$today,
			  "packing_list_cpy"=>$today,
			  "cert"=>"",
			  "cert_ori"=>$today,
			  "cert_cpy"=>$today,
			  "insurance"=>"",
			  "insurance_ori"=>$today,
			  "insurance_cpy"=>$today,
			  "loa"=>"",
			  "loa_ori"=>$today,
			  "loa_cpy"=>$today,
			  "stat_con"=>"",
			  "stat_con_ori"=>$today,
			  "stat_con_cpy"=>$today,
			  "recom_loa"=>"",
			  "recom_loa_ori"=>$today,
			  "recom_loa_cpy"=>$today,
	          "recom_lartas"=>"",
	          "recom_lartas_ori"=>$today,
	          "recom_lartas_cpy"=>$today
	       )
	   
	   );
	   
	   
   }
   
      
}

else
{
   $ResultProject  = array(	
      array(

         "jo_id" => "",
         "jo_code" => "",
         "doc_ref" => "",
         "project_id" => "",
         "debtur" => "",
         "staff_id" =>"",
         "jo_date" =>$today,
         "bl_no" => "",
         "invoice_no" => "",
         "vessel" => "",
         "rbt_idr" =>"",
         "rbt_usd" =>"",
         "rat_idr" =>"",
         "rat_usd" =>"",
         "jo_appv_status" =>""

      )
   );

   //SELECT * FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'Foo'

}

//SET UPLOAD LIST
$SQLUploadFile = "SELECT * FROM tblshipping_doc_upload WHERE jo_id ='".$jo_id."' ORDER BY upload_doc_id ASC";
$ResultUploadFile = $DBConnection->dbc->get_results($SQLUploadFile,ARRAY_A);


if(!empty($ResultUploadFile))
{
	foreach($ResultUploadFile as $idx => $val)
	{
		$uploadList.= "- <a href='".$ServerURL."/".$ROOT_UPLOAD_DIR."/".$uploadDirModule."/".$val['file_upload']."'>".$val['file_upload']."</a><br/>";		
	}
}

else
{
	$uploadList = "";
}

//Project
$shipment_arr = explode(".",$ResultProject[0]['jo_code']);
$shipment = $shipment_arr[2];

$HeaderFields = array("jo_id"=>"","jo_code"=>"","project_id"=>"project_id","debtur"=>"debtur","staff_id"=>"staff_id","jo_date"=>"date","rbt_idr"=>"","rbt_usd"=>"","rat_idr"=>"","rat_usd"=>"","jo_appv_status" => "");

//Leave Here Untouch
$FormHName     = BuildHTMLField($HeaderFields,"name",1);
$FormHValue    = BuildHTMLField($HeaderFields,"value",1);

$SQLHeader     = "SELECT ".BuildFields($HeaderFields)." FROM $TableName ";


//Edited by Adit van Smith
$SQLCustomer = "SELECT * FROM ".$DBGeneral.".tbldebitur ORDER BY CUNAME ASC";
//End Edited by Adit van Smith

$SQLgetProject = "SELECT * FROM tblproject ORDER BY project_name ASC";




// HTML Value
$TBS->MergeBlock("headbln",$FormHName);
$TBS->MergeBlock("headblv",$ResultProject);
$TBS->MergeBlock("headblv2",$ResultProject2);


//********************************* HTML GRID *********************************************
//HTML Grid

$SQLGrid = "SELECT * FROM tblshipping_doc_remarks 
            WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' ORDER BY remarks_id ";

$Result  = $DBConnection->dbc->get_results($SQLGrid,ARRAY_A);
$Result  = BuildEmptyGrid ($FormFields, $MaxGrid, $Result);

$TBS->MergeBlock("blg",$Result);
$TBS->Show();

//*************** ACTION FUNCTION *******************


function redirectMeta($url)
{
	echo "Redirecting.... Please Wait.....";
	echo "<meta http-equiv='refresh' content='0;url=".$url."'>";
}

function jsAlert($msg)
{
	$msg = str_replace("\n","\\n",$msg);
	
	echo '<script>
	      alert("'.$msg.'");	
	      </script>';
}

function FormInsert() {
        global $DBConnection,$FileName;
        $DBConnection->Insert();
        header("Location: $FileName?PageMode=Form");
        exit;
}

function FormUpdate() {
        global $DBConnection;
        $DBConnection->Update();
}

function FormDelete() {
        global $DBConnection,$FileName,$TableName;
        $DBConnection->deleteGrid("$TableName","nobkt");
        header("Location: $FileName");
        exit;
}

function FormSearch () {

}

function FormCancel () {
        global $FileName;
        header("Location: ".$FileName."?PageMode=List");
        exit;
}


function FormSave ($table, $keyField, $FormFields, $SpecialCase="", $PrimaryKey, $PrimaryKeyVal="") {	    
        global $FileName, $MaxGrid, $DBConnection;
        $TotalData = $MaxGrid * 2;
        $NewDataStart = GetParam("NewData","0");
        $NewDataStart = 1;



        for ($a=1;$a<=$MaxGrid;$a++) {
	    //Begin For

            
            if (GetParam($keyField.$a,""))
            {
			//Begin Check if Empty Keyfield	
            
                 
                foreach ($FormFields as $key=>$formatting) {

                        if(!empty($PrimaryKeyVal))
                        {
                            $value = GetParam($key.$a,"");

                            if ($formatting=="number") $value = str_replace(",","",$value);
                            if ($formatting=="date")
                            {
                                    list($day,$month,$year) = explode("/",$value);
                                    $value = "$year-$month-$day";
                            }
                            //Inser if the key is equal primary key, then set valu = primary header
                            if($key == "$PrimaryKey")
                            {
                               $DBConnection->add_data($table,$key,$PrimaryKeyVal);
                            }

                            else
                            {
                               $DBConnection->add_data($table,$key,$value);
                            }

                        }

                        else
                        {
                            $value = GetParam($key.$a,"");

                            if ($formatting=="number") $value = str_replace(",","",$value);
                            if ($formatting=="date")
                            {
                                    list($day,$month,$year) = explode("/",$value);
                                    $value = "$year-$month-$day";
                            }

                            $DBConnection->add_data($table,$key,$value);

                        }

                }

                $rate = StrToNumber(GetParam("rate",""));
                $jmh  = StrToNumber(GetParam("jumlah".$a,""));

                // Add by Chandra (15 May 2009)
                $cash_type = GetParam("cash_type","");
                //var_dump($cash_type); exit;



                if($cash_type) $DBConnection->add_data($table,'cash_type',$cash_type);
                // end update


                if (strlen($SpecialCase)) 
                {
                        foreach ($SpecialCase as $key => $value) 
                        {
                                //print "add_data($table,$key,$value);<br>";
                                $DBConnection->add_data($table,$key,$value);
                        }
                }

//                print "$a < $NewDataStart<br>";
                if ($a < $NewDataStart) 
                {
                         if (strlen($PrimaryKey)) 
                         {
                            $DBConnection->UpdateGrid($PrimaryKey,GetParam($PrimaryKey.$a,""));
                         } 
                         else 
                         {
                            $DBConnection->UpdateGrid($keyField,GetParam($keyField.$a,""));
                         }
                } 
                
                else 
                {
                        $DBConnection->InsertGrid();
//                        $DBConnection->dbc->debug();
                }
            
            
            //End Check if Empty Keyfield
            }
            
            
        //End For    
        }
        $DBConnection->ClearData();
}


//*************** USER FUNCTION *******************

function buildsqlfield ($table, $arrayfield) {
        global $DBConnection;
        foreach ($arrayfield as $key=>$Formatting) {
            $value = GetParam($key,"");
            if ($Formatting=="date") {
                list($day,$month,$year) = explode("/",$value);
                $value = "$year-$month-$day";
            } elseif ($Formatting=="number") $value = str_replace(",","",$value);
            $DBConnection->add_htmlfield($table,$key,$value);
        }
}


function DeleteRecord ($sequence_name,$PageSize) {
        global $DBConnection,$FileName,$TableName;
        for ($x=1;$x<=$PageSize;$x++) {
                if (GetParam($sequence_name.$x,""))        {
                        $DBConnection->deleteGrid("$TableName","memorial_id",$sequence_name.$x);
            }
        }
}

function BuildFields ($FormFields) {
                global $DBConnection;
                $str = "";
                foreach ($FormFields as $key=>$formatting) {
                        if (strlen($str)) $str .= ",$key";
                        else $str = "$key";
                }
                return $str;
}

function MutatorFields ($FormFields, $MaxGrid) {
                global $DBConnection;
                $array_fields = array();
                for ($x=0;$x<$MaxGrid;$x++) {
                        foreach ($FormFields as $key=>$formatting){
                                $a=$x+1;
                                $array_fields[$key.$a] = "$formatting";
                        }
                }
                return $array_fields;
}

function FlushCustomer ($TableName, $tmp) {
        global $DBConnection;

        if ($tmp) $TEMPORARY = "TEMPORARY";
        $DBC = new mydb(DB_USER, DB_PASSWORD, DB_NAME2, DB_HOST);

        $SQL = "SELECT kodecustomer,nama,cr_term,kdtype FROM customer ";
        if (GetParam("kdtype","")) $SQL .= " WHERE kdtype='".GetParam("kdtype","")."'";
        $MyResult = $DBC->dbc->get_results($SQL,ARRAY_N);
        if (!$MyResult) return false;
         $session_file = substr(md5(time()), 0, 8);
           $session_file = "/tmp/".$session_file.".tmp";
        BufferToFile ($MyResult,$session_file);

        $DBConnection = new mydb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
        $SQL = "DROP TABLE IF EXISTS `$TableName`;";
        $DBConnection->dbc->query($SQL);

        $SQL= "CREATE $TEMPORARY TABLE `$TableName` (
                          `kodecustomer` varchar(20) NOT NULL default '',
                          `nama` varchar(50) default NULL,
                          `cr_term` int(4) default NULL,
                          `kdtype` varchar(20) default NULL
                          )";
        $DBConnection->dbc->query($SQL);

           $SQL = "LOAD DATA INFILE '$session_file' INTO TABLE $TableName FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'";
        $DBConnection->dbc->query($SQL);
        unlink($session_file);
        return true;
}

function GetLastDateReport() {
        global $DBConnection;
        list($day,$month,$year) = explode("/",GetParam("tglbkt",""));
        $current_date = "$year-$month-$day";

    $SQL = "DELETE FROM ais_piutang_sisa WHERE aging_date>='$current_date' ";
    if (GetParam("curr","")) $SQL .= " AND curr='".GetParam("curr","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND fromskada = '".GetParam("skada999","")."' ";
    if (GetParam("skada999","")) $SQL .= " AND toskada = '".GetParam("skada999","")."' ";
    $DBConnection->dbc->query($SQL);
    //$DBConnection->dbc->debug();

        $SQL = "SELECT max(aging_date) FROM ais_piutang_sisa WHERE aging_date<='$current_date' ";
        if (GetParam("curr","")) $SQL .= " AND curr='".GetParam("curr","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND fromskada = '".GetParam("skada999","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND toskada = '".GetParam("skada999","")."' ";

        return $DBConnection->dbc->get_var($SQL);
}

function convert_code($code,$digit)
{
		
	$length = strlen($code);	
	$tot_str = $digit - $length;	
	$code_edit = "";
	
	for($i=0;$i < $tot_str; $i++)
	{
		$code_edit.= "0";
	}
	
	$code_edit.= $code;
	
	return $code_edit;
	
}

function convert_date($dateVar)
{
	if(!empty($dateVar))
	{
		list($day,$month,$year) = explode("/",$dateVar);
		$dateResult  = "$year-$month-$day";	
    }
	
	else
	{
		$dateResult = "";
	}
	
    return $dateResult;
}



?>
